/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kosongkosong.scheduler;

import com.kosongkosong.model.Story;
import com.kosongkosong.service.DataService;
import com.kosongkosong.utils.UrlUtils;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.cyberneko.html.parsers.DOMParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static com.kosongkosong.scheduler.UrlConstants.*;
/**
 *
 * @author ifnu
 */
@Controller
public class HeadlineParserScheduler {

//    private static final Log LOGGER = LogFactory.getLog(HeadlineParserScheduler.class);
    
    @Autowired private DataService dataService;

    @RequestMapping(value="/parse-headline",method=RequestMethod.GET)
    public void parseHeadLine(HttpServletResponse response) throws Exception{
        //fetch url
        String newsString = UrlUtils.fetchUrl(WC_2010);
        //ambil image
        Story story = parseStory(newsString);
        Story persistenceStory = dataService.getStory(story.getId());
        //ambil full story
        String fullStory = UrlUtils.fetchUrl(story.getStoryUrl());
        //parse isi story
        parseCompleteStory(story, fullStory);
        story.setHeadline(Boolean.TRUE);
        if(persistenceStory==null){
            dataService.saveHeadline(story);
        } else {
            dataService.delete(persistenceStory);
            dataService.saveHeadline(story);
        }
        response.getOutputStream().close();
    }
    
    /**
     * utils method
     */

    String getStoryId(String href){
        int storyIdIndex = href.indexOf("=");
        int ampIndex = href.indexOf("&");
        return href.substring(storyIdIndex+1,ampIndex);
    }

    Story parseStory(String newsString){
        try{
            DOMParser parser = new DOMParser();
            parser.parse(new InputSource(new StringReader(newsString)));
            //get main page URL
            Document d  = parser.getDocument();
            NodeList nodeList = d.getElementsByTagName("div");
            Story story = new Story();

            for(int i=0;i<nodeList.getLength();i++){
                Node node = nodeList.item(i);
                NamedNodeMap map = node.getAttributes();
                if(map!=null){
                    Node classAttribute = map.getNamedItem("class");
                    if(classAttribute!=null){
                        String classAttributeValue = classAttribute.getNodeValue();
                         if(classAttributeValue!=null && classAttributeValue.equals("subHead bold")){
                            NodeList subHeadChilds = node.getChildNodes();
                            if(subHeadChilds.getLength()==1){
                                Node subHeadA = subHeadChilds.item(0);
                                story.setSubHeader(subHeadA.getTextContent());
                                NamedNodeMap subHeadMap = subHeadA.getAttributes();
                                String href = subHeadMap.getNamedItem("href").getNodeValue();
                                story.setStoryUrl(SOCCERNET + href);
                                //parse story href
                                story.setId(getStoryId(href));
                                //cek apakah story ini udah ada di dalam datastore
                            }
                        } else if(classAttributeValue!=null && classAttributeValue.equals("headline")){
                            story.setHeader(node.getTextContent());
                        } else if(classAttributeValue!=null && classAttributeValue.equals("topImage")){
                            NodeList topImageChilds = node.getChildNodes();
                            if(topImageChilds.getLength()==1){
                                Node tomImageImg = topImageChilds.item(0);
                                story.setSubHeader(tomImageImg.getTextContent());
                                NamedNodeMap subHeadMap = tomImageImg.getAttributes();
                                String imgSrc = subHeadMap.getNamedItem("src").getNodeValue();
                                story.setImageUrl(imgSrc);
                            }
                        }
                    }
                }
            }
            return story;
        } catch (SAXException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    Story parseCompleteStory(Story story, String html){
        try {
            DOMParser parser = new DOMParser();
            parser.parse(new InputSource(new StringReader(html)));
            //get main page URL
            Document d = parser.getDocument();
            NodeList nodeList = d.getElementsByTagName("div");

            for(int i=0;i<nodeList.getLength();i++){
                Node node = nodeList.item(i);
                NamedNodeMap map = node.getAttributes();
                if(map!=null){
                    Node classAttribute = map.getNamedItem("class");
                    if(classAttribute!=null){
                        String classAttributeValue = classAttribute.getNodeValue();
                         if(classAttributeValue!=null && classAttributeValue.equals("ind story")){
                            story.setFullStory(node.getTextContent());
                            break;
                         }
                    }
                }
            }

        } catch (SAXException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return story;
    }

}
